package com.jiubanqingchen.org.role;

import com.jfinal.aop.Aop;
import com.jfinal.plugin.activerecord.Record;
import com.jiubanqingchen.framework.annotation.SqlKey;
import com.jiubanqingchen.framework.base.service.ModelService;
import com.jiubanqingchen.framework.base.user.IUser;
import com.jiubanqingchen.framework.exception.WishException;
import com.jiubanqingchen.framework.security.AuthService;
import com.jiubanqingchen.model.models.Role;
import com.jiubanqingchen.org.resourceAuthority.ResourceAuthorityService;
import com.jiubanqingchen.org.userGroupRole.UserGroupRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author light_dust
 * @since 2021/1/4 11:44
 */
@SqlKey("org_role.list")
public class RoleService extends ModelService<Role> {

    private final static Logger logger = LoggerFactory.getLogger(RoleService.class);

    @Override
    public void afterDelete(Role role, Record record, IUser _usr) throws WishException {
        //角色删除后 我们需要把角色关联的数据一并清理掉 不然会造成很多垃圾数据存在
        String roleId = role.getRoleId();
        String roleName = role.getRoleName();

        //删除角色与部门的关联
        UserGroupRoleService userGroupRoleService = Aop.get(UserGroupRoleService.class);
        userGroupRoleService.deleteWhere("roleId=?", roleId);
        logger.info("正在删除角色 [{}]({}) 与部门/用户相关联的数据...", roleName, roleId);

        //删除角色与资源相关联的数据
        ResourceAuthorityService resourceAuthorityService = Aop.get(ResourceAuthorityService.class);
        resourceAuthorityService.deleteWhere("roleId=?", roleId);
        logger.info("正在删除角色 [{}]({}) 与资源权限相关联的数据...", roleName, roleId);

        //清理角色在缓存中的所有权限
        AuthService authService = Aop.get(AuthService.class);
        authService.deleteRoleCache(roleId);

        //这里有待考量 需不要要把在线用户的角色也给他干掉
        super.afterDelete(role, record, _usr);
    }
}
